<!--历史数据-->
<template>
  <div class="historyContainer">
    <!--导航栏-->
    <van-nav-bar
      title="历史数据"
      @click-left="goBack"
      fixed
      :border="true"
      :z-index="100"
      class="my-nav-bar"
    >
      <span class="el-icon-arrow-left fontsize" slot="left"></span>
    </van-nav-bar>
    <!--搜索-->
    <div class="topheader">
      <div class="f flexwrap fb">
        <div class="search f fs" @click="showPickerstart = true">
          {{ start_date }}
        </div>
        <div class="search f fs" @click="isend">
          {{ end_date }}
        </div>
        <div class="search f fs" @click="showPickerType = true">
          {{ yjtype }}
        </div>
      </div>
      <!--开始时间-->
      <van-popup v-model="showPickerstart" position="bottom">
        <van-datetime-picker
          type="date"
          @cancel="showPickerstart = false"
          @confirm="onConfirmstart_date"
          v-model="currentDate"
        />
      </van-popup>
      <!--结束时间-->
      <van-popup v-model="showPickerend" position="bottom">
        <van-datetime-picker
          type="date"
          @cancel="showPickerend = false"
          @confirm="onConfirmend_date"
          v-model="currentDate"
        />
      </van-popup>
      <!--预警类型-->
      <van-popup v-model="showPickerType" position="bottom">
        <van-picker
          show-toolbar
          :columns="typecolumns"
          @cancel="showPickerType = false"
          @confirm="onConfirmtype"
        />
      </van-popup>
    </div>
    <!--列表-->
    <van-tabs v-model="active" class="my-tabs" @click="tabClick">
      <van-tab
        title="历史数据"
        class="purchase_echart_tabs"
        @click="tabTap(item.act)"
      >
        <div>
          <van-list
            v-model="loading"
            :finished="finished"
            finished-text="没有更多了"
            :error.sync="error"
            error-text="请求失败，点击重新加载"
            class="my-list"
            @load="init"
          >
            <el-table
              stripe
              style="width: 100%"
              :data="buyThingTable"
              :header-cell-style="{
                'background-color': '#5A92FF',
                color: '#ffffff',
                border: 'none',
              }"
            >
              <el-table-column prop="" label="监测值" align="center"  width="70">
                <template slot-scope="scope">
                  {{
                    scope.row.monitoringValue ? scope.row.monitoringValue : "/"
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="" label="标准值" align="center"  width="70">
                <template slot-scope="scope">
                  {{ scope.row.standardValue ? scope.row.standardValue : "/" }}
                </template>
              </el-table-column>
              <el-table-column prop="" label="发布值" align="center"  width="70">
                <template slot-scope="scope">
                  {{
                    scope.row.wbReleaseValue ? scope.row.wbReleaseValue : "/"
                  }}
                </template>
              </el-table-column>
              <el-table-column prop="" label="监测时间" align="center"  >
                <template slot-scope="scope">
                  <p>
                    {{
                      spli1(scope.row.createdTime)[0]
                        ? spli1(scope.row.createdTime)[0]
                        : "/"
                    }}
                  </p>
                  <p>
                    {{
                      spli1(scope.row.createdTime)[1]
                        ? spli1(scope.row.createdTime)[1]
                        : "/"
                    }}
                  </p>
                </template>
              </el-table-column>
              <el-table-column prop="" label="状态" align="center"  width="70">
                <template slot-scope="scope">
                  {{ scope.row.state == 0 ? "预警" : "正常" }}
                </template>
              </el-table-column>
            </el-table>
          </van-list>
        </div>
      </van-tab>
      <van-tab
        title="预警分析"
        class="purchase_echart_tabs"
        @click="tabTap(item.act)"
      >
        <div class="echartyj">
          <div class="chartdiv" id="main1"></div>
        </div>
      </van-tab>
    </van-tabs>
  </div>
</template>
<script>
const currentDate = new Date();
import echarts from "echarts";
import moment from "moment";
var projectId = localStorage.getItem("projectid");
import { findPagePMHistoryData, earlyWarningAnalysis } from "@/api/api";
export default {
  data() {
    return {
      activeTab: [
        { act: 0, title: "PM2.5" },
        { act: 1, title: "PM10" },
      ],
      //list状态
      loading: false, //是否处于加载状态
      finished: false, //是否已加载完成
      error: false, //是否加载失败，加载失败后点击错误提示可以重新触发load事件，必须使用sync修饰符
      //分页
      paging: { page: 1, rows: 12 },
      active: 0, //左右滑块
      //表格
      buyThingTable: [],
      showSearch: false,
      showdate: false,
      showStatus: false,
      Statuscolumns: [
        { keyId: 1, text: "PM2.5" },
        { keyId: 2, text: "PM10" },
      ],
      historyOption: {},
      source: 1,
      showPickerdate: false,
      date: "请选择开始时间",
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2050, 0, 31),
      time: {
        startTime: moment().format("YYYY-MM-DD"), // 开始时间
        endTime: moment().format("YYYY-MM-DD"), // 结束时间
      }, // 时间查询
      //预警
      typecolumns: [
        { keyId: 1, text: "PM2.5" },
        { keyId: 2, text: "PM10" },
      ],
      yjtype: "请选择PM",
      yjid: 1,
      showPickerType: false,
      start_date: "请选择开始时间", //开始时间
      end_date: "请选择结束时间", //结束时间
      showPickerend: false,
      showPickerstart: false,
      signdate: "", //出生日期
      currentDate1: new Date(),
      currentDate: currentDate,
    };
  },
  mounted() {
    setTimeout(() => {
      this.yjfx();
    }, 500);
  },
  methods: {
    spli1(date) {
      if (date != null) {
        return date.split(" ");
      }
    },
    //判断是
    isend() {
      if (isNaN(this.start_date) && !isNaN(Date.parse(this.start_date))) {
        this.showPickerend = true;
      } else {
        this.$toast({
          message: "请先选择开始时间",
          className: "my-toast",
        });
      }
    },
    //开始时间
    onConfirmstart_date(val) {
      this.start_date = moment(val).format("YYYY-MM-DD");
      this.showPickerstart = false;
    },

    //结束时间
    onConfirmend_date(val) {
      this.end_date = moment(val).format("YYYY-MM-DD");
      if (moment(this.end_date).isBefore(this.start_date)) {
        this.$toast({
          message: "结束时间不能大于开始时间,请重新选择",
          className: "my-toast",
        });

        this.showPickerend = false;
        this.end_date = "请选择结束时间";
      } else {
        this.time.endTime = this.end_date;
        this.time.startTime = this.start_date;
        this.buyThingTable = [];
        this.paging.page = 1;
        this.init();
        this.yjfx();
        this.showPickerend = false;
      }
    },
    goBack() {
      this.$router.go(-1); //返回上一层
    },

    tabTap(act) {
      var that = this;
      that.active = act;
    },
    tabClick(index) {
      var that = this;
      if (index == 1) {
        that.$nextTick(() => {
          // dom元素更新后执行，因此这里能正确打印更改之后的值
          that.yjfx();
        });
      }
    },
    search() {
      this.paging.page = 1;
      this.buyThingTable = [];
      this.init();
    },
    yjfx() {
      var params = {
        projectId: projectId,
        source: this.yjid,
        startDate: this.time.startTime,
        endDate: this.time.endTime,
      };

      //历史分析
      this.Request(earlyWarningAnalysis(params)).then((res) => {
        if (res.status == "200") {
          var data = res.body;
          const dataset = data.map((item) => [
            moment(item.date).format("M-D"),
            item.measured,
            item.beforeHourMeasured,
          ]);
          const total = data.reduce(
            (count, item) => count + item.beforeHourMeasured,
            0
          );

          var echarts = require("echarts");
          // 基于准备好的dom，初始化echarts实例
          var myChart = echarts.init(document.getElementById("main1"));

          // 绘制图表
          var historyOption = {
            subtitle: `累计预警 ${total}次`,
            legend: {
              left: "center",
              bottom: 0,
            },
            tooltip: {},
            dataset: {
              source: [["product", "实测值", "前一小时平均值"], ...dataset],
            },
            xAxis: { type: "category" },
            yAxis: {
              type: "value",
              name: "单位（次）",
            },
            series: [
              {
                type: "bar",
                itemStyle: {
                  color: "#498afe",
                },
                label: {
                  normal: {
                    show: true,
                    position: "top",
                  },
                },
              },
              {
                type: "bar",
                itemStyle: {
                  color: "#ff9800",
                },
                label: {
                  normal: {
                    show: true,
                    position: "top",
                  },
                },
              },
            ],
          };
          myChart.setOption(historyOption);
        } else {
          this.$message({
            type: "error",
            message: res.Message,
            center: "true",
          });
        }
      });
    },
    // 获取数据
    init() {
      var params = {
        projectId: projectId,
        page: this.paging.page,
        pageSize: this.paging.rows,
        startDate: this.time.startTime,
        endDate: this.time.endTime,
        source: this.yjid,
      };
      //历史数据
      this.Request(findPagePMHistoryData(params)).then((res) => {
        if (res.status == "200") {
          this.total = Number(res.body.total);
          this.buyThingTable.push(...res.body.records);
          // 数据全部加载完成
          if (this.paging.page * this.paging.rows >= res.body.total) {
            this.finished = true;
          } else {
            this.finished = false;
          }
          this.paging.page += 1;
        } else {
          this.$message({
            type: "error",
            message: res.message,
            center: "true",
          });
        }
        this.loading = false;
      });
    },
    formatDate(date) {
      return `${date.getMonth() + 1}/${date.getDate()}`;
    },
    onDateConfirm(values) {
      const [start, end] = values;
      this.time.endTime = this.start_date;
      this.time.startTime = this.end_date;
      this.date = `${this.formatDate(start)} - ${this.formatDate(end)}`;
      this.showPickerdate = false;
      this.buyThingTable = [];
      this.paging.page = 1;
      this.init();
      this.yjfx();
    },
    //预警类型
    onConfirmtype(value) {
      this.yjtype = value.text;
      this.yjid = value.keyId;
      this.showPickerType = false;
      this.buyThingTable = [];
      this.paging.page = 1;
      this.init();
      this.yjfx();
    },
    //时间段
    onConfirm() {},
  },
};
</script>
<style lang="stylus" scoped>
@import '~@/assets/css/resetVant.css';

/deep/ .van-calendar__day--start, /deep/ .van-calendar__day--end, /deep/ .van-button--danger {
  background-color: #5b8dee;
  border: #5b8dee;
}

/deep/ .van-picker__cancel, /deep/.van-picker__confirm, /deep/.van-picker-column {
  font-size: 30px !important;
}

/deep/.van-calendar__day--middle {
  color: #5b8dee;
}

.topheader {
  width: 100%;
  padding: 20px 20px 10px;
  box-sizing: border-box;
  margin-bottom: 30px;
  background: #fff;

  .flexwrap {
    flex-wrap: wrap;
  }

  .search {
    -webkit-appearance: none;
    width: 48%;
    border: 1px solid #eee;
    height: 60px;
    border-radius: 5px;
    padding-left: 10px;
    box-sizing: border-box;
    margin-bottom: 10px;
    font-size: 28px;
  }

  input::-webkit-input-placeholder {
    /* WebKit browsers */
    color: #000;
  }

  .searchBtn {
    width: 120px;
    height: 62px;
    background: #5b8dee;
    color: #fff;
    border-radius: 5px;
  }

  .f {
    display: flex;
    justify-content: flex-start;
    align-items: center;

    &.fs {
      justify-content: flex-start;
    }

    &.fe {
      justify-content: flex-end;
    }

    &.fc {
      justify-content: center;
    }

    &.fa {
      justify-content: space-around;
    }

    &.fb {
      justify-content: space-between;
    }

    &.fn {
      flex-direction: column;
    }

    &.fp {
      flex-wrap: wrap;
    }

    &.vfs {
      align-items: flex-start;
    }

    &.vfe {
      align-items: flex-end;
    }
  }

  .fl {
    flex: 1;
  }
}

.echartyj {
  width: 100%;
  height: 500px;

  .chartdiv {
    width: 100%;
    height: 100%;
  }
}

.my-popup {
  height: 100%;
  width: 70%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  background-color: white;

  .my-radio {
    height: 80px;
    display: flex;
    align-items: center;

    /* border-bottom: 1px #E5E5E5 solid; */
    /deep/.van-radio__label {
      margin-left: 30px;
      font-size: 30px;
    }
  }

  .my-radio:last-child {
    border-bottom: 0;
  }

  .popupCont {
    width: 100%;
    padding: 40px;
    box-sizing: border-box;

    .title {
      font-size: 32px;
      font-weight: bold;
      margin-bottom: 30px;
      color: #595959;

      .timeicon {
        font-size: 40px;
        margin-right: 20px;
        color: #1989fa;
      }
    }

    .date {
      width: 100%;
      height: 60px;
      border: 1px solid #ccc;
      margin-bottom: 30px;
    }
  }

  .screening-btn {
    display: flex;
    justify-content: space-around;
    margin: 40px 0;

    /deep/.van-button {
      width: 40%;
    }

    .van-button--primary {
      background-color: #FFBA00;
      border: 1px solid #FFBA00; /* no */
    }
  }
}

.historyContainer {
  width: 100%;
  height: 100%;
  padding-top: 88px;
  box-sizing: border-box;

  .ai_report_nav_img img {
    height: 37px;
    width: 41px;
  }

  /deep/.van-tabs__line {
    background-color: #5b8dee;
  }

  /deep/.van-tabs__nav .van-tab--active .van-ellipsis {
    color: #5b8dee;
  }

  .van-tabs--line {
    // padding-top: 110px;
  }

  /* 表格样式更改 */
  /deep/.el-table .cell {
    padding: 15px 0;
    font-size: 24px;
  }

  /deep/ .el-table .table_input {
    border: 2px solid #5893ff;
  }
}

/deep/.el-table__header-wrapper .el-table__header, .el-table__body-wrapper .el-table__body, .el-table__body, .el-table__footer-wrapper .el-table__footer {
  width: 100% !important;
}

/deep/.el-table__body, .el-table__footer, .el-table__header {
  table-layout: initial !important;
}

.my-tabs .el-table__footer-wrapper, .my-tabs .el-table__header-wrapper {
  overflow: auto;
}
</style>
